package com.dosin.crowno;

import com.dosin.crowno.pojo.UserAccount;
import com.dosin.crowno.service.MainService;
import com.dosin.crowno.service.UserAccountService;
import com.dosin.crowno.utils.FileWriteAndRead;
import com.dosin.crowno.utils.SSLinitialize;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.concurrent.Worker;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class MainController1 {

    WebEngine engine;
    @Resource
    UserAccountService userAccountService;

    @Resource
    MainService mainService;


    @FXML
    private Label usernameText;

    @FXML
    private Label daoqidateText;

    @FXML
    private Label versionText;


    @FXML
    private ChoiceBox ipChoiceText;

    @FXML
    private ChoiceBox portChoiceText;

    @FXML
    private ChoiceBox websiteChoiceText;

    @FXML
    private ChoiceBox levelSelect;

    @FXML
    private Button netLoginButton;

    @FXML
    private TextField userTextField;

    @FXML
    private TextField netPasswordText;

    @FXML
    private TextField safetyCodeTextField;

    @FXML
    WebView webView;

    static String cookieStr = "";

    @FXML
    public void initialize() throws URISyntaxException, IOException {

        //初始化SSL连接
        SSLinitialize.initialize();
        engine = webView.getEngine();



    /*    URI uri = URI.create("https://ag.hga008.com");
        Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>();
        headers.put("Set-Cookie", Arrays.asList("name=value"));
        try {
             java.net.CookieHandler.getDefault().put(uri, headers);
            System.out.println(java.net.CookieHandler.getDefault().get(uri, headers));
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }*/


        engine.setJavaScriptEnabled(true);
        engine.setUserAgent("Mozilla/5.0 (compatible; ABrowse 0.4; Syllable)");

    /*     cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);*/
        //Set<Cookie> cookies =cookieStr;

        URI uri = URI.create("https://ag.hga008.com");
        Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>();
        cookieStr = FileWriteAndRead.readFile("d:/data.txt");
        System.out.println("登录页面显示cookie:"+cookieStr);
        headers.put("Set-Cookie", Arrays.asList(cookieStr));




        CookieHandler.getDefault().put(uri, headers);

        engine.load("https://ag.hga008.com");

        engine.setJavaScriptEnabled(true);

        engine.getLoadWorker().stateProperty().addListener(new ChangeListener() {


            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                if (newValue == Worker.State.SUCCEEDED) {
                   System.out.println( engine.getLocation());

                  // Cookie cookie = getCookies();
                    //System.out.println(CookieUtils.getCookies(engine.getLocation()));



                    Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>();
                  //  cookieStr = FileWriteAndRead.readFile("d:/data.txt");
                    System.out.println("登录页面显示cookie:"+cookieStr);
                    headers.put("Set-Cookie", Arrays.asList(cookieStr));


                }
            }



                });









    }

    protected void openMainWindow(UserAccount user, TextField usernameTextField) throws IOException {

        Stage mainStage = new Stage();
        mainStage.setScene(new Scene(CrownoApplication.loadFxml("/server.fxml").load()));

        System.out.println(getClass().getResource("/images").toString());
        mainStage.getIcons().add( new Image(getClass().getResource("/images/crownt.png").toString()));
        mainStage.setTitle("新皇冠（服务端）1.1.1.0 - 服务端口：1111 - 服务密码：88888");
        usernameText.setText(user.getUsername());
        SimpleDateFormat sf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        daoqidateText.setText(sf.format(user.getDueDate()));
        if(user.getVersion()==0){
        versionText.setText("正式");
        }else if(user.getVersion() ==1){
            versionText.setText("测试");
        }else{
            versionText.setText("临时用户");
        }



/*        https://ag.hga008.com
        https://ag.hga025.com
        https://ag.hga030.com
        https://ag.hga0088.com*/

        List list = new ArrayList();
        List ips = new ArrayList();
        List levels = new ArrayList();
        list.add("https://ag.hga008.com");
        list.add("https://ag.hga025.com");
        list.add("https://ag.hga030.com");
        list.add("https://ag.hga0088.com");
        levels.add(1);
        levels.add(2);
        levels.add(3);
        ips.add("127.0.0.1");

        ipChoiceText.setItems(FXCollections.observableArrayList(ips));
        ipChoiceText.setValue(ips.get(0));


        portChoiceText.setItems(FXCollections.observableArrayList(1111));
        portChoiceText.setValue(1111);



        websiteChoiceText.setItems(FXCollections.observableArrayList(list));
        websiteChoiceText.setValue(list.get(0));

        levelSelect.setItems(FXCollections.observableArrayList(levels));
        levelSelect.setValue(levels.get(2));





      /*  webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load("https://www.baidu.com/");*/

        mainStage.show();





        Window window = usernameTextField.getScene().getWindow();
        if(window instanceof Stage){
            ((Stage) window).close();
        }






        mainStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                System.out.print("监听到窗口关闭");
                user.setIsLogin(0);
                userAccountService.updateByPrimaryKeySelective(user);
                System.exit(0);
            }
        });
    }


    public void netLoginButtonAction(){
        //System.out.println(websiteChoiceText.getValue());
        String website = (String) websiteChoiceText.getValue();
        String username =userTextField.getText();
        String passwd = netPasswordText.getText();
        String level = levelSelect.getValue().toString();
        String safetyCode = safetyCodeTextField.getText();
        netLoginButton.setDisable(true);
       // mainService.loginWebSite(website,username,passwd,level,safetyCode,cookieStr);

    }


    public void netLoginButtonAction1(){
        //System.out.println(websiteChoiceText.getValue());
        String website = "https://hga030.com/";
        String username ="zz0417";
        String passwd = "azz0417";
        String level = levelSelect.getValue().toString();
        String safetyCode = safetyCodeTextField.getText();

       // mainService.loginWebSite1(website,username,passwd,level,safetyCode,cookieStr);

    }






}
